<template>
  <div class="windows_top">
    <div class="windows_top_box">
      <span class="selected_none" v-if="currentChatType === 'friend'">{{
        currentChat.user_alias
      }}</span>
      <span class="selected_none"
        v-if="currentChatType === 'group'">{{ currentChat.group_name }}({{ currentChat.userNUm }})</span>
    </div>
  </div>
  <!--聊天内容-->
  <div class="windows_body">
    <div class="office_text">
      <el-scrollbar ref="msgScrollBar">
        <ul class="content" id="chatbox">
          <template v-for="(message, idx) in currentChat.messageList" :key="message.create_timestamp">
            <li class="selected_none" v-if="message.from === currentChat.user_id">
              <p class="time" v-show="showMsgTime(idx)">
                <span>{{ formatTime(message.create_timestamp) }}</span>
              </p>
              <div class="other main">
                <img :src="currentChat.avatar" :title="currentChat.realname" />
                <p class="text" v-html="message.content"></p>
              </div>
            </li>
            <li class="selected_none" v-else>
              <p class="time" v-show="showMsgTime(idx)">
                <span>{{ formatTime(message.create_timestamp) }}</span>
              </p>
              <div class="me main">
                <img :src="userInfo.avatar" :title="userInfo.realname" />
                <p class="text" v-html="message.content"></p>
              </div>
            </li>
          </template>
        </ul>
      </el-scrollbar>
    </div>
  </div>
  <div class="windows_input" id="talkbox">
    <div class="input_icon">
      <el-popover placement="top" :width="500" trigger="click" popper-class="chat-panel-emoji"
        v-model:visible="emojiVisible">
        <template #reference>
          <span @click="emojiVisible = !emojiVisible"></span>
        </template>
        <el-scrollbar>
          <div class="face-panel">
            <img v-for="face in faceList" class="face-panel-img" :key="face.value" :src="getEmojiUrl(face.src)"
              :alt="face.value" @click="insertEmoji(face.src)" />
          </div>
        </el-scrollbar>
      </el-popover>
      <!-- 文件 -->
      <span></span>
      <!-- 截图 -->
      <span @click="screenshot"></span>
      <!-- 历史记录 -->
      <span></span>
      <span></span>
      <span></span>
    </div>
    <div class="input_box">
      <!-- <textarea name="" rows="" cols="" id="input_box"></textarea> -->
      <el-scrollbar>
        <p contenteditable="true" ref="inputBox" @click="handleBoxClick" enterkeyhint="send" class="input_content"
          spellcheck="false" @input="onSendInput"></p>
      </el-scrollbar>
      <button class="message_send" @click="doSend">发送(s)</button>
    </div>
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from "vue";
import { useChatStore } from "../../../store/chat";
import { useUserStore } from "../../../store/user";
import { formatChatDate } from "../../../utils/utils";
import { chatFace, getAssetsFile } from "../../../utils/emoji";
import kscreenshot from "kscreenshot";
import socket from "../../../utils/socket_io";
import { saveFriendMsg } from "../../../service/chat";

let rangeOfInputBox;
export default defineComponent({
  name: "chat-panel",
  setup() {
    const msgScrollBar = ref();
    const chatStore = useChatStore();
    const userStore = useUserStore();
    const currentChat = computed(() => chatStore.currentChat);
    const currentChatType = computed(() => chatStore.currentChatType);
    const userInfo = computed(() => userStore.userInfo);
    const sendContent = ref("");
    const inputBox = ref();
    const faceList = ref({});
    const emojiVisible = ref(false);
    const ksreenshot = ref(null);
    const onSendInput = (e) => {
      sendContent.value = e.target.innerText
        .trim()
        .replace(/(\r\n|\r|\n)/g, " ")
        .replace(/\s+/, " ");
    };
    const showMsgTime = (idx) => {
      let flag = true;
      if (idx != 0) {
        flag =
          currentChat.value.messageList[idx].create_timestamp -
            currentChat.value.messageList[idx - 1].create_timestamp -
            1000 * 60 * 1 >
          0
            ? true
            : false;
      }
      return flag;
    };
    const formatTime = (num) => {
      return formatChatDate(num, "yyyy-MM-dd hh:mm:ss");
    };
    const handleScollBottom = () => {
      nextTick(() => {
        msgScrollBar.value.wrap$.scrollTop =
          msgScrollBar.value.wrap$.scrollHeight;
      });
    };
    const getEmojiUrl = (url) => {
      return getAssetsFile(url);
    };
    const handleBoxClick = (event) => {
      let target = event.target;
      setCaretForEmoji(target);
    };
    const setCaretForEmoji = (target) => {
      if (target.tagName.toLowerCase() === "img") {
        let range = new Range();
        range.setStartBefore(target);
        range.collapse(true);
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(range);
      }
    };
    const insertEmoji = (name) => {
      emojiVisible.value = false;
      let emojiEl = document.createElement("img");
      emojiEl.width = 28;
      emojiEl.height = 28;
      emojiEl.src = getEmojiUrl(name);

      if (!rangeOfInputBox) {
        rangeOfInputBox = new Range();
        rangeOfInputBox.selectNodeContents(inputBox.value);
      }

      if (rangeOfInputBox.collapsed) {
        rangeOfInputBox.insertNode(emojiEl);
      } else {
        rangeOfInputBox.deleteContents();
        rangeOfInputBox.insertNode(emojiEl);
      }
      rangeOfInputBox.collapse(false);
    };
    const doSend = () => {
      let content = inputBox.value.innerHTML;
      saveFriendMsg({
        to: currentChat.value.user_id,
        content,
      }).then(() => {
        const create_timestamp = Date.now();
        chatStore.currentChatSendMsg({
          currentChat: currentChat.value,
          from: userInfo.value.user_id,
          content,
          messageType: 1,
          create_timestamp,
        });
        handleScollBottom();
        socket.emit("sendPrivateMsg", {
          from: userInfo.value.user_id,
          to: currentChat.value.user_id,
          content,
          messageType: 1,
          create_timestamp,
        });
      });
      // todo 发送消息
      inputBox.value.innerHTML = "";
    };
    const handleInputSelectChange = () => {
      document.onselectionchange = () => {
        let selection = document.getSelection();
        if (selection.rangeCount > 0) {
          const range = selection.getRangeAt(0);

          if (inputBox.value.contains(range.commonAncestorContainer)) {
            rangeOfInputBox = range;
          }
        }
      };
    };
    const screenshot = () => {
      ksreenshot.value.startScreenShot();
    };
    const handleInputPasteChange = () => {
      inputBox.value.addEventListener("paste", function (e) {
        if (!(e.clipboardData && e.clipboardData.items)) {
          return;
        }
        for (let i = 0, len = e.clipboardData.items.length; i < len; i++) {
          let item = e.clipboardData.items[i];
          if (item.kind === "string") {
            // todo 取消粘贴的标签
            item.getAsString(function (str) {
              let reg2 = /<(?!img).*?>/gi; //匹配除img标签外的html标签  不包括html标签内的内容
              let content = str.replace(reg2, "");
              return content;
            });
          } else if (item.kind === "file") {
            let pasteFile = item.getAsFile();
            // pasteFile就是获取到的文件
          }
        }
      });
    };
    watch(
      () => currentChat.value.messageList,
      () => {
        nextTick(() => {
          handleScollBottom();
        });
      },
      { deep: true }
    );
    onMounted(() => {
      faceList.value = chatFace;
      handleScollBottom();
      handleInputSelectChange();
      handleInputPasteChange();
      ksreenshot.value = new kscreenshot({
        key: 65,
        // needDownload: true,
        endCB: (data) => {
          let shotEl = document.createElement("img");
          shotEl.src = data;
          if (!rangeOfInputBox) {
            rangeOfInputBox = new Range();
            rangeOfInputBox.selectNodeContents(inputBox.value);
          }

          if (rangeOfInputBox.collapsed) {
            rangeOfInputBox.insertNode(shotEl);
          } else {
            rangeOfInputBox.deleteContents();
            rangeOfInputBox.insertNode(shotEl);
          }
          rangeOfInputBox.collapse(false);
        },
        cancelCB: (data) => {
          console.log(data, "cancelCB");
        },
      });
    });
    onUnmounted(() => {
      document.onselectionchange = () => {
        return false;
      };
    });
    return {
      userStore,
      emojiVisible,
      inputBox,
      userInfo,
      currentChat,
      currentChatType,
      msgScrollBar,
      sendContent,
      faceList,
      screenshot,
      showMsgTime,
      formatTime,
      handleScollBottom,
      onSendInput,
      getEmojiUrl,
      insertEmoji,
      handleBoxClick,
      doSend,
      handleInputSelectChange,
      handleInputPasteChange,
    };
  },
});
</script>

<style lang="less" scoped>
@import "src/pages/wechat/wechat.less";
.windows_top {
  padding-top: 10px;
  height: 62px;
  border-bottom: 1px solid #e7e7e7;

  .windows_top_box {
    width: 100%;
    height: 100%;
    position: relative;

    & > span {
      font-size: 18px;
      color: #333;
      line-height: 52px;
      padding-left: 30px;
      display: inline-block;
    }
  }
}
.windows_body {
  height: 473px;
  width: 100%;
  .office_text {
    height: calc(100% - 12px);
  }
  p {
    padding: 5px 10px;
    margin-top: 10px;
    border-radius: 4px;
  }

  /*区分聊天*/

  .content {
    width: 100%;
    padding: 10px 20px;
    .time {
      margin: 7px 0;
      text-align: center;
      span {
        display: inline-block;
        padding: 4px 18px 2px;
        font-size: 12px;
        color: #fff;
        border-radius: 2px;
        background-color: #dcdcdc;
      }
    }
    .me {
      margin-top: 10px;
      padding-left: 10px;
      display: block;
      clear: both;
      overflow: hidden;
      margin-bottom: 5px;
      display: flex;
      flex-direction: row-reverse;
      img {
        width: 34px;
        height: 34px;
        border-radius: 2px;
      }

      .text {
        background: #9eea6a;
        padding: 7px;
        border-radius: 4px;
        margin: 0 10px;
        max-width: 80%;
        border: 1px solid #9eea6a;
        position: relative;
        color: #000000;
        word-break: break-all;
        cursor: pointer;
        user-select: auto;
        &:before {
          content: " ";
          position: absolute;
          top: 9px;
          border: 6px solid transparent;
          border-left-color: #9eea6a;
          left: 100%;
        }
      }
    }

    .other {
      margin-top: 10px;
      padding-left: 10px;
      width: 80%;
      display: block;
      clear: both;
      overflow: hidden;
      margin-bottom: 5px;
      display: flex;
      img {
        width: 34px;
        height: 34px;
        border-radius: 2px;
      }

      .text {
        background: #fff;
        padding: 7px;
        border-radius: 4px;
        margin: 0 10px;
        max-width: 80%;
        border: 1px solid #ededed;
        position: relative;
        color: #000000;
        word-break: break-all;

        &:before {
          content: " ";
          position: absolute;
          top: 9px;
          right: 100%;
          border: 6px solid transparent;
          border-right-color: #ffffff;
        }
      }
    }
  }
}

.windows_input {
  border-top: 1px solid #ececec;
  height: 145px;
  width: 100%;

  .input_icon {
    height: 42px;
    padding: 0 28px;

    span {
      position: relative;
      display: inline-block;
      height: 20px;
      width: 24px;
      margin-top: 11px;
      margin-right: 8px;
      cursor: pointer;
    }

    span:nth-child(1) {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon13.png)
        no-repeat center center;
    }

    span:nth-child(1):hover {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon13_1.png)
        no-repeat center center;
    }

    span:nth-child(2) {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon14.png)
        no-repeat center center;
    }

    span:nth-child(2):hover {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon14_1.png)
        no-repeat center center;
    }

    span:nth-child(3) {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon15.png)
        no-repeat center center;
    }

    span:nth-child(3):hover {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon15_1.png)
        no-repeat center center;
    }

    span:nth-child(4) {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon16.png)
        no-repeat center center;
    }

    span:nth-child(4):hover {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon16_1.png)
        no-repeat center center;
    }

    span:nth-child(6) {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon17.png)
        no-repeat center center;
      float: right;
    }

    span:nth-child(6):hover {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon17_1.png)
        no-repeat center center;
    }

    span:nth-child(5) {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon18.png)
        no-repeat center center;
      float: right;
    }

    span:nth-child(5):hover {
      background: url(https://fengnull.gitee.io/picture_house/icon/icon18_1.png)
        no-repeat center center;
    }

    span img {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
}

.input_box {
  height: 62px;

  .input_content {
    position: relative;
    width: calc(100% - 56px);
    height: 62px;
    cursor: text;
    background: #fefefe;
    resize: none;
    outline: none;
    margin-left: 28px;
    font-size: 14px;
    line-height: 20px;
    border: none;
    color: #252933;
    white-space: pre-wrap;
    overflow: auto;
  }
  textarea {
    width: calc(100% - 56px);
    height: calc(100% - 42px);
    border: none;
    outline: 0;
    background: #fefefe;
    resize: none;
    margin-left: 28px;
    font-size: 14px;
    line-height: 20px;
  }

  .message_send {
    border: 1px solid #e5e5e5;
    background: #f5f5f5;
    color: #666;
    padding: 0 8px;
    outline: 0;
    height: 26px;
    float: right;
    margin-top: 8px;
    margin-right: 18px;
    cursor: pointer;

    &:hover {
      background: #09bb07;
      color: #fff;
      border: 1px solid #09bb07;
    }
  }
}
</style>
<style lang="less">
.dark-theme {
  .chat-panel-emoji {
    &.el-popper[role="tooltip"] {
      min-width: 100px;
      background: white;
      color: #303133;
      border-color: #e5e7eb;
    }
    &.is-light.el-popper[role="tooltip"] .el-popper__arrow:before {
      border-color: rgb(228, 231, 237);
      background: white;
    }
    .face-panel {
      display: flex;
      flex-wrap: wrap;
      height: 300px;
      overflow: auto;
      .face-panel-img {
        width: 28px;
        height: 28px;
        margin: 12px;
        cursor: pointer;
      }
    }
  }
}
</style>